import React, { useState, useEffect, useMemo, useRef } from 'react';
import { Modal, Button, Skeleton, Image, message, Upload, Row, Col, Space, Tag, Tabs, Divider, Slider, InputNumber } from 'antd'
import type { SliderMarks } from 'antd/es/slider';
import { UploadOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';
import { ProFormDigit, ProFormInstance } from '@ant-design/pro-components';

import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  ProCard,
  CheckCard,
  ProFormRadio,
  ModalForm,
  ProFormCheckbox
} from '@ant-design/pro-components';

import CheckboxList from './CheckboxList';
import InputNumberItem from './InputNumberItem'


import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade,
  reqWesternMedicineList,
  reqBaseFormulaList,
  reqBaseFormulaDetailList,
  reqEtiologyCategoryList,
  reqEtiologyList,
  reqEtiologyCategoryListByDiagnosis,
  reqSeniorInquiryPrescriptionMedication,
  reqBaseFormulaDetailGetBaseFormulaHerb,
  getTyHerbList,
  reqAggregationHotDataList
} from '@/services/firstConsultation';


import styles from '../index.module.less'

const EditModalAdd: React.FC = ({
  isOpen,
  user,
  handleModal,
  seletTyDiagnosisIds,
  baseFormulaMap,
  closeModal
}: {
  isOpen: boolean,
  user: any,
  handleModal: Function,
  seletTyDiagnosisIds?: any,
  baseFormulaMap?: any,
  closeModal: Function,
}) => {

  const [formObj] = ProForm.useForm()
  const modalFormRef = useRef<ProFormInstance>();
  const [data, setData] = useState([])

  const [medicineList, setMedicineList] = useState<any>([])



  // useEffect(() => {
  //   if (defArr && defArr?.length > 0 && data && data?.length > 0) {
  //     const initList = defArr.map((item: any) => item?.id)
  //     setSelectList(initList)
  //   }
  // }, [defArr, data])



  async function init(query = {}) {
    const errLogName = '中药材信息列表'
    try {
      Object.assign(query, { "pageSize": 1000 });
      const res = await getTyHerbList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        const mapArr = res?.data?.result?.map((item: any) => ({
          medicineId: item?.id,
          label: item?.name,
          quantity: 10
        }))
        // return mapArr;
        // return res?.data?.result
        setData(mapArr)

      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }


  async function getTyBaseFormulaIds() {
    const errLogName = '获取汤济药材信息列表'
    try {
      const res = await reqBaseFormulaDetailGetBaseFormulaHerb({ tyBaseFormulaIds: seletTyDiagnosisIds })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        const mapArr = res?.data?.map((item: any) => ({
          medicineId: item?.tyHerbId,
          label: item?.tyHerbName,
          quantity: item?.quantity
        }))
        setMedicineList(mapArr)

      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }

  const [hotDataList, setHotDataList] = useState()

  async function getHotDataList(query = {}) {
    const errLogName = '常用数据列表'
    try {
      const res = await reqAggregationHotDataList({ ...query })
      console.log(`${errLogName}信息 :>> `, res?.data);
      if (res?.resultCode == '00000000') {
        const mapArr = res?.data?.result?.map((item: any) => ({
          medicineId: item?.id,
          label: item?.name,
          quantity: 10
        }))
        setHotDataList(mapArr)
      } else {
        message.error(`${errLogName}信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error(`${errLogName}信息出错！`, error)
      console.log(`${errLogName}信息出错！ :>> `, error);
    }
  }

  useEffect(() => {
    init()
    getHotDataList({
      pageNum: 1,
      pageSize: 10,
      // 类型，[1:中药,2:西药,3:汤剂,4:针灸]
      type: 1
    })
  }, [])

  useEffect(() => {
    getTyBaseFormulaIds()
  }, [seletTyDiagnosisIds])

  async function onFinish(values: any) {
    console.log('onFinish====> :>> ', values);
    const { cookingTime2, ...other } = values;
    const res = await reqSeniorInquiryPrescriptionMedication({
      id: user?.seniorInquiry?.id,
      receiveMethod: user?.receiveMethod,
      medicineType: 1,
      medicineList: medicineList?.map((item: any) => ({
        medicineId: item?.medicineId,
        quantity: item?.quantity
      })),
      baseFormula: {
        ...other,
        tyBaseFormulaIds: seletTyDiagnosisIds,
      }
    });
    if (res?.resultCode == '00000000') {
      handleModal(false)
      closeModal(false)
      message.success('开方完成，请提醒病人前往药房付费')
    } else {
      message.error(`系统异常！${res?.message}`)
    }
  }

  const marks: SliderMarks = {
    0: '50%',
    50: '100%',
    150: '200%',
  };


  function onChangeCheckboxList(array: any) {
    console.log('onChangeCheckboxList :>> ', array, medicineList);
    if (!array || array.length == 0) return;
    let newArray: any = []
    array.forEach((item: any) => {
      let exist = -1;
      for (let i = 0; i < medicineList.length; i++) {
        if (medicineList[i].medicineId == item.medicineId) {
          exist = i;
        }
      }
      if (exist > -1) {
        newArray.push({ ...item, quantity: item?.quantity });
        //   medicineList[exist].quantity = item?.quantity;
      } else {
        newArray.push(item);
      }
    });
    console.log('onChangeCheckboxList++++ :>> ', newArray);
    // setMedicineList(medicineList.concat(newArray));
    setMedicineList(newArray);
  }


  // console.log('baseFormulaMap :>> ', baseFormulaMap);

  return (
    <Modal
      width={'80vw'}
      style={{
        minHeight: '60vh'
      }}
      title="散方汤剂"
      open={isOpen}
      onCancel={() => handleModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <div>
        <div className={styles.header}>
          <div>
            {
              seletTyDiagnosisIds.map((item: any, index: number) => (
                <b key={index} className={styles.sname}>
                  {index != 0 && '+'}
                  {
                    baseFormulaMap &&
                    baseFormulaMap[item] &&
                    baseFormulaMap[item]?.name
                  }
                </b>
              ))
            }
          </div>
          <Space>
            <Button type='primary' onClick={() => handleModal(false)}>更换经方</Button>
          </Space>
        </div>
        <ProForm
          form={formObj}
          layout="horizontal"
          // initialValues={initialValues}
          onFinish={(values): Promise<any> => onFinish(values)}
          submitter={{
            // 配置按钮文本
            searchConfig: {
              resetText: '重置',
              submitText: '保存',
            },
          }}
        >
          <Row gutter={24}>
            <Col span={24}>
              <Row gutter={[24, 24]}>
                {
                  medicineList?.map((item: any, index: number) => (
                    <Col span={6} key={index}>
                      <InputNumberItem
                        data={medicineList}
                        {...item}
                        index={index}
                        onChange={onChangeCheckboxList}
                      />
                    </Col>
                  ))
                }
              </Row>
              <ModalForm
                title="增减药材"
                formRef={modalFormRef}
                trigger={
                  <Button
                    style={{ marginTop: 20 }}
                    icon={<PlusOutlined />}
                    type='primary'
                  >增减药材</Button>
                }
                submitTimeout={1000}
                width={'80vw'}
                style={{
                  minHeight: '60vh'
                }}
                submitter={{
                  render: (props, defaultDoms) => {
                    return [
                      ...defaultDoms,
                    ];
                  },
                }}
                onFinish={async (values) => {
                  console.log(values);
                  message.success('提交成功');
                  return true;
                }}
              >
                <>
                  <CheckboxList medicineList={medicineList} data={data} hotDataList={hotDataList} onChange={onChangeCheckboxList} />
                </>
              </ModalForm>
            </Col>
            {/* <Col span={24}>
              <ProForm.Item
                label="药量倍率"
                name='magnification'
              >
                <Slider
                  tipFormatter={(value) => <span>{value + 50}%</span>}
                  marks={marks}
                  max={150}
                  step={10}
                  defaultValue={50}
                />
              </ProForm.Item>
            </Col> */}
          </Row>
          <Divider />
          <Row gutter={24}>
            <Col span={12}>
              <ProFormSelect
                placeholder="请选择用药时间"
                label="用药时间"
                name='administrationTime'
                rules={[{ required: true }]}
                options={[
                  {
                    label: '朝九 晚五',
                    value: '朝九 晚五',
                  },
                  {
                    label: '早后 晚后',
                    value: '早后 晚后',
                  },
                  {
                    label: '早后 午后 晚后',
                    value: '早后 午后 晚后',
                  },
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormDigit name="quantity"
                rules={[{ required: true }]}
                label="用药剂数"

                placeholder="请输入用药剂数"></ProFormDigit>
            </Col>
            <Col span={12}>
              <ProFormSelect
                placeholder="请选择一剂几包"
                label="一剂几包"
                name='packets'
                rules={[{ required: true }]}
                options={[
                  {
                    label: '1包',
                    value: '1',
                  },
                  {
                    label: '2包',
                    value: '2',
                  }, {
                    label: '3包',
                    value: '3',
                  }, {
                    label: '4包',
                    value: '4',
                  }, {
                    label: '5包',
                    value: '5',
                  }, {
                    label: '6包',
                    value: '6',
                  }, {
                    label: '7包',
                    value: '7',
                  }, {
                    label: '8包',
                    value: '8',
                  }, {
                    label: '9包',
                    value: '9',
                  }, {
                    label: '10包',
                    value: '10',
                  }
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormSelect
                placeholder="请选择服药间隔"
                label="服药间隔"
                name='administrationInterval'
                rules={[{ required: true }]}
                options={[
                  {
                    label: '0天',
                    value: '0',
                  },
                  {
                    label: '1天',
                    value: '1',
                  },
                  {
                    label: '2天',
                    value: '2',
                  },
                  {
                    label: '3天',
                    value: '3',
                  },
                  {
                    label: '4天',
                    value: '4',
                  },
                  {
                    label: '5天',
                    value: '5',
                  },
                  {
                    label: '6天',
                    value: '6',
                  },
                  {
                    label: '7天',
                    value: '7',
                  },
                  {
                    label: '8天',
                    value: '8',
                  },
                  {
                    label: '9天',
                    value: '9',
                  },
                  {
                    label: '10天',
                    value: '10',
                  },
                  {
                    label: '11天',
                    value: '11',
                  },
                  {
                    label: '12天',
                    value: '12',
                  },
                  {
                    label: '13天',
                    value: '13',
                  },
                  {
                    label: '14天',
                    value: '14',
                  },
                  {
                    label: '15天',
                    value: '15',
                  }
                ]}
              />
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={8}>
              <ProFormDependency
                name={['cookingTime']}
                shouldUpdate={(prevValues, curValues) => (
                  prevValues.cookingTime !== curValues.cookingTime
                )}
              >
                {({ cookingTime }) => {
                  cookingTime && cookingTime != 60 && cookingTime != 120 && formObj.setFieldValue('cookingTime2', undefined)
                  return (
                    <ProFormRadio.Group
                      name="cookingTime2"
                      label="煮药时长"
                      // disabled={cookingTime2}
                      // rules={[
                      //   {
                      //     required: true,
                      //     message: '请选择煮药时长'
                      //   }
                      // ]}
                      options={[
                        {
                          label: '60分钟',
                          value: '60',
                        },
                        {
                          label: '120分钟',
                          value: '120',
                        },
                      ]}
                    />
                  );
                }}
              </ProFormDependency>
            </Col>
            <Col span={16}>
              <ProFormDependency
                name={['cookingTime2']}
                shouldUpdate={(prevValues, curValues) => (
                  prevValues.cookingTime2 !== curValues.cookingTime2
                )}
              >
                {({ cookingTime2 }) => {
                  cookingTime2 && formObj.setFieldValue('cookingTime', cookingTime2)
                  return (
                    <ProFormText
                      rules={[{ required: true, message: '请输入用煮药时长' }]}
                      name="cookingTime"
                      // disabled={cookingTime}
                      placeholder="请输入用煮药时长"
                    />
                  );
                }}
              </ProFormDependency>
            </Col>
          </Row>
          <Divider />
          <Row gutter={24}>
            <Col span={12}>
              <ProFormTextArea
                name="toMedicineStoreRemark"
                label="备注给药房"
                placeholder="请输入药房备注"
              />
            </Col>
            <Col span={12}>
              <ProFormTextArea
                name="toPatientRemark"
                label="备注给患者"
                placeholder="请输入患者备注"
              />
            </Col>
          </Row>
        </ProForm>
      </div>
    </Modal >
  );
};
export default EditModalAdd;

